package android_testsuite.mytest.network_test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

import android_testsuite.mytest.util.Const;


public class Tcp {
    private int mPort;
    private String mHost;
    private Selector mSelector;

    public Tcp() {
        mHost = Const.HOST;
        mPort = Const.PORT;
    }

    public Tcp(String host, int port) {
        mHost = host;
        mPort = port;
    }

    //处理连接请求
    public void connectAction(SelectionKey key) {
        SocketChannel sc = (SocketChannel) key.channel();
        try {
            sc.configureBlocking(false);
            sc.register(mSelector, SelectionKey.OP_READ);
            sc.finishConnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //处理读请求
    public void readAction(SelectionKey key) {
        ByteBuffer buffer = ByteBuffer.allocate(Const.BUFFER_SIZE);
        SocketChannel sc = (SocketChannel) key.channel();
        int readBytes = 0;
        try {
            int ret = 0;
            try {
                while ((ret = sc.read(buffer)) > 0) {
                    readBytes += ret;
                }
            }  catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                buffer.flip();
            }

            if (readBytes > 0) {
                System.out.println(Charset.forName("UTF-8").decode(buffer).toString());
                buffer = null;
            }
        } finally {
            if (buffer != null) {
                buffer.clear();

            }
        }
    }



    public void run() throws IOException {
        //打开选择器
        mSelector = Selector.open();
        //打开通道
        SocketChannel channel = SocketChannel.open();
        //设置为非阻塞模式
        channel.configureBlocking(false);
        //创建网络地址
        SocketAddress target = new InetSocketAddress(mHost, mPort);
        //申请连接
        channel.connect(target);
        //给选择器注册连接事件
        channel.register(mSelector, SelectionKey.OP_CONNECT);
        System.out.println("please input the information to send, ended by quit");
        //建立输入信息流
        BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in));

        while (true) {
            if (channel.isConnected()) {
                String command = systemIn.readLine();
                channel.write(Charset.forName("UTF-8").encode(command));

                if (command == null || "quit".equalsIgnoreCase(command.trim())) {
                    systemIn.close();
                    channel.close();
                    mSelector.close();
                    System.out.println("Client quit !");
                    System.exit(0);
                }
            }

            int nKeys = mSelector.select(1000);
            if (nKeys > 0) {
                for (SelectionKey key : mSelector.selectedKeys()) {
                    if (key.isConnectable()) {
                        connectAction(key);
                    } else if (key.isReadable()) {
                        readAction(key);
                    }
                }
                mSelector.selectedKeys().clear();
            }
        }
    }

}
